<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * API2 class for customer (customer)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Silk_Mapi_Model_Api2_Account_Rest_Customer_V1 extends Silk_Mapi_Model_Api2_Account_Rest
{
    public function _retrieveCollection()
    {
        $status = $this->getRequest()->getParam('status');
        /** @var Mage_Sales_Model_Mysql4_Order_Collection $collection */
        $collection = $this->getOrderCollection();

        switch ($status) {
            case 'refund':
                $collection->addFieldToFilter('total_refunded', array('gt' => 0))
                    ->addOrder('entity_id');
                break;
            case 'pending':
                $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_PENDING)
                    ->addOrder('entity_id');
                break;
            case 'processing':
                $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_PROCESSING)
                    ->addOrder('entity_id');
                break;
            case 'delivering':
                $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_DELIVERING)
                    ->addOrder('entity_id');
                break;
            default:
                return array(
                    'pending' => $this->getPendingCount(),
                    'processing' => $this->getProcessingCount(),
                    'delivering' => $this->getDeliveringCount(),
                    'refund' => $this->getRefundCount()
                );
        }

        $orders = array();
        foreach ($collection as $item) {
            $orders[] = $this->_formatOrderItem($item);
        }
        return $orders;
    }

    /**
     * Retrieve information about customer
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        //$token = Mage::getModel('mapi/token')->loadByToken($this->getRequest()->getHeader('Access-Token'));
        $customer = $this->_loadCustomerById($this->getApiUser()->getUserId());
        $account = Mage::helper('rewardpoints/customer')->getAccountByCustomer($customer);
        //$subscriber = Mage::getModel('newsletter/subscriber')->loadByCustomer($customer);
        $result = array(
            //'customer_id' => $customer->getId(),
            //'firstname' => $customer->getFirstname(),
            //'lastname' => $customer->getLastname(),
            //'username' => $customer->getUsername(),
            //'mobile' => $customer->getMobile(),
            'points' => (int)$account->getPointBalance()
            //'access_token' => $token->getToken(),
            //'access_token_secret' => $token->getTokenSecret()
        );
        //$result['is_subscribed'] = $subscriber->isSubscribed() ? true : false;

        return $result;
    }

    /**
     * Retrieve collection with only current customer instance
     *
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        return parent::_getCollectionForRetrieve()->addAttributeToFilter('entity_id', $this->getApiUser()->getUserId());
    }

    /**
     * Update customer
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
        if ($this->_isOwner($this->getRequest()->getParam('id'))) {
            parent::_update($data);
        }
    }

    /**
     * Is customer has rights to retrieve/update customer item
     *
     * @param int $customerId
     * @throws Mage_Api2_Exception
     * @return bool
     */
    protected function _isOwner($customerId)
    {
        if ($this->getApiUser()->getUserId() !== $customerId) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return true;
    }

    /**
     * Update customers
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _multiUpdate(array $data)
    {
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }

    protected function _delete()
    {
        $access_token = $this->getRequest()->getHeader('Access-Token');
        $token = Mage::getModel('mapi/token')->loadByToken($access_token);
        if ($token && $token->getId()) $token->delete();
        return array();
    }

    protected function getOrderCollection()
    {
        $customerId = $this->getApiUser()->getUserId();
        $collection = Mage::getModel('sales/order')->getCollection()
            ->addFieldToFilter('customer_id', $customerId);

        return $collection;
    }

    protected function getPendingCount()
    {
        $collection = $this->getOrderCollection();
        $orders = $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_PENDING);

        return (int)$orders->getSize();
    }

    protected function getProcessingCount()
    {
        $collection = $this->getOrderCollection();
        $orders = $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_PROCESSING);

        return (int)$orders->getSize();
    }

    protected function getDeliveringCount()
    {
        $collection = $this->getOrderCollection();
        $orders = $collection->addFieldToFilter('status', Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_DELIVERING);

        return (int)$orders->getSize();
    }

    protected function getRefundCount()
    {
        $collection = $this->getOrderCollection();
        $orders = $collection->addFieldToFilter('total_refunded', array('gt' => 0));

        return (int)$orders->getSize();
    }

    protected function _formatOrderItem(Mage_Sales_Model_Order $item, $timeFormat = 'Y-m-d')
    {
        $createdAt = date($timeFormat, Mage::getModel('core/date')->timestamp($item->getCreatedAt()));
        $statusCode = $item->getStatus();
        $status = $item->getStatusLabel();

        if ($item->hasCreditmemos()) {
            if ($item->getCreditmemosCollection()->addFieldToFilter('source', 1)->count()) {
                $statusCode = 'order_money_refund';
                $status = '有退款';
            } else {
                $statusCode = 'order_item_refund';
                $status = '有退货';
            }
        }

        return array(
            'id' => (int)$item->getId(),
            'increment_id' => $item->getIncrementId(),
            'created_at' => $createdAt,
            'status_code' => $statusCode,
            'status' => $status,
            'subtotal' => (float)$item->getSubtotal(),
            'grand_total' => (float)($item->getGrandTotal() - $item->getTotalRefunded()),
        );
    }
}
